import { getTemplates, getTemplateById } from '@/api/template'
import { saveRecord } from '@/api/record'

const template = {
  state: {
    // templates: JSON.parse(localStorage.getItem('templates')),
    templates: null,
    tempOpen: null
  },

  mutations: {
    SET_TEMPLATES: (state, templates) => {
      state.templates = templates
    },
    SET_TEMP_OPEN: (state, tempOpen) => {
      if (tempOpen && typeof tempOpen.PE.values == 'string') {
        tempOpen.PE.values = JSON.parse(tempOpen.PE.values)
      }
      state.tempOpen = tempOpen
    }
  },

  actions: {
    // 获取菜单信息
    getTemplates({ commit, state }, ifForceGet) {
      if (!state.templates || ifForceGet) {
        return new Promise((resolve, reject) => {
          getTemplates().then(res => {
            // localStorage.setItem('templates', JSON.stringify(res.data))
            commit('SET_TEMPLATES', res.data)
            resolve(res.data)
          }).catch(err => {
            reject(err)
          })
        })
      } else {
        return state.templates
      }
    },
    getTemplateById({ commit, state }, templateId) {
      if (!state.tempOpen) {
        return new Promise((resolve, reject) => {
          getTemplateById(templateId).then(res => {
            commit('SET_TEMP_OPEN', res.data)
            resolve(res.data)
          }).catch(err => {
            reject(err)
          })
        })
      } else {
        return state.tempOpen
      }
    },
    saveRecord({ commit, state }, templateId) {
      return new Promise((resolve, reject) => {
        saveRecord(state.tempOpen, templateId).then(res => {
          commit('SET_TEMP_OPEN', res.data.record)
          resolve(res)
        }).catch(err => {
          reject(err)
        })
      })
    }
  }
}

export default template
